package com.zcsy.manage.distribution.service.base.impl;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.zcsy.commons.constants.DistributionConstants;
import com.zcsy.commons.model.RequestJson;
import com.zcsy.manage.distribution.service.base.CCommonTokenService;
import com.zcsy.manage.model.base.CommonToken;
import com.zcsy.manage.persistence.base.CommonTokenDao;

/**
 * 
 * @Title:CCommonTOkenServiceImpl
 * @Package：  com.zcsy.manage.distribution.service.base.impl
 * @Description:token 接口实现类
 * @author wangj
 * @date 2016年6月17日上午9:45:24
 * @version 1.0
 * @see JDK1.7.0_67
 * @Copyright: 2016 武汉恒数利通技术有限公司 All rights reserved.
 */
@Service
public class CCommonTOkenServiceImpl implements CCommonTokenService {
	
	@Autowired
	private CommonTokenDao commontokendao;

	@Override
	public int insert(CommonToken commonToken) {
		return commontokendao.insert(commonToken);
	}

	@Override
	public CommonToken selectByToken(String token) {
		CommonToken cToken = commontokendao.selectByToken(token);
		Date date = new Date();
		if (cToken == null) {
			CommonToken intoCommonToken = new CommonToken();
			intoCommonToken.setTokenMessage(DistributionConstants.OTHER_DEVICES_LOGIN);//帐号在其他设备登录
			
			return intoCommonToken;
		} else {
			if ((date.compareTo(cToken.getExpireTime()))<0) {
				return cToken;
				
			} else {
				CommonToken intoCommonToken = new CommonToken();
				intoCommonToken.setTokenMessage(DistributionConstants.INVALID_LOGIN); //用户授权失效
				
				return intoCommonToken;
			}
		}
	}

	@Override
	public CommonToken selectByAccount(String account) {
		return commontokendao.selectByAccount(account);
	}

	@Override
	public int updateToken(CommonToken commonToken) {
		return commontokendao.updateToken(commonToken);
	}

	/**
 	 * 
 	 * @Description 订单概览交互状态<br>
 	 * 
 	 * @param dtoken 会话
 	 * @param result 返回结果
 	 * @return 
 	 * @author lilan 1063972142@qq.com
 	 * @date 2016年6月20日
 	 * @see
 	 */
	@Override
	public RequestJson OrderInteractState(String dtoken , RequestJson result){
		
		CommonToken tokenInfo = selectByToken(dtoken);
		int tokenMessage = tokenInfo.getTokenMessage();
		
		if (tokenInfo.getId() == null) {
			result.setSuccess(false);
			
			if (tokenMessage == DistributionConstants.OTHER_DEVICES_LOGIN) {
				result.setResultCode(tokenMessage);
				result.setMsg("帐号在其他设备登录");
				
			}
			if (tokenMessage == DistributionConstants.INVALID_LOGIN) {
				result.setResultCode(tokenMessage);
				result.setMsg("用户授权失效请重新登录");
				
			}
		}
		
		return result;
	}
}
